<template>
	<view class="viewbox auto p-top30 p-bot100">
		<block v-for="(item,index) in ruleForm" :key="index">
			<!-- 多列选择器 -->
			<view class="list" :class="{'required':item.required}" v-if="item.type == 1">
				<picker mode="multiSelector" class="viewData " :range="classify" range-key="classify_name"
					@columnchange="columnchange" @change="changeClass($event,index)">
					<view class="viewPicker">
						<view class="flex-1" :class="{'Default':!item.title}">{{item.title?item.title:item.placeholder}}
						</view>
						<image src="../../static/right.png" class="rightMore"></image>
					</view>
				</picker>
			</view>

			<!-- 单行输入框 -->
			<view class="list" :class="{'required':item.required}" v-if="item.type == 3">
				<input type="text" class="viewData" v-model="item.value" :placeholder="`${item.placeholder}`" />
			</view>

			<!-- 图片 -->
			<view class="list_medium" v-if="item.type == 5">
				<view class="title" :class="{'required_med':item.required}">{{item.title}}</view>
				<view class="row">
					<block v-if="item.value.length">
						<view class="list_imgs" v-for="(item,sindex) in item.value.slice(0,item.num)" :key="sindex">
							<image :src="$imgUrls(item)" mode="aspectFill" class="upload"></image>
							<image src="../../static/close.png" class="Close" @click="closeImg(index,sindex)"></image>
						</view>
					</block>
					<view class="list_imgs" @click="Upload(item.num,index)" v-if="item.value.length < item.num">
						<image src="../../static/upload.png" class="upload"></image>
					</view>
				</view>
			</view>

			<!-- 商品详情 -->
			<view class="list_medium" v-if="item.type == 6">
				<view class="title" :class="{'required_med':item.required}">{{item.title}}</view>
				<sp-editor :toolbar-config="toolbarConfig" :readOnly="readOnly" @input="inputOver($event,index)"
					@upinImage="upinImage" @init="initEditor($event,item.value)"></sp-editor>
				<!-- <textarea class="textarea" :maxlength="-1" v-model="item.value" disable-default-padding
					:placeholder="`请输入${item.placeholder}`"></textarea> -->
			</view>


			<!-- 单行输入框 数字 -->
			<view class="list" :class="{'required':item.required}" v-if="item.type == 7">
				<input type="numeric" class="viewData" v-model="item.value" :placeholder="`${item.placeholder}`" />
			</view>

			<!-- 单行输入框 价格带小数点 -->
			<view class="list" :class="{'required':item.required}" v-if="item.type == 8">
				<input type="decimal" class="viewData" v-model="item.value" :placeholder="`${item.placeholder}`" />
			</view>

			<!-- 单选 -->
			<view class="list_medium" v-if="item.type == 9">
				<view class="title" :class="{'required_med':item.required}">{{item.title}}</view>
				<view class="row">
					<view class="radio" :class="{'radioActive':item.value == ditem.value}"
						v-for="(ditem,dindex) in item.data" :key="dindex" @click.stop="RadioBtn(ditem,index,dindex)">
						<text class="radioName">{{ditem.name}}</text>
						<view class="radioRound"></view>
					</view>

				</view>
			</view>

		</block>

		<view class="row j-sa m-top80">
			<view class="reSet bot_btn" @click="reset">重置</view>
			<view class="subMit bot_btn" @click="subMit">提交</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	/*
	   type 1 多列选择器
	        2 普通选择器
			3 单行输入框 文字
			5 图片 num为图片数量
			6 多行输入框
			7 单行输入框 数字
			8 单行输入框 价格带小数点
			9 单选
			10 多选
	*/

	export default {
		data() {
			return {
				goods_id: '',
				ruleForm: [],
				classify: [],
				editorIns: null,
				readOnly: false,
				toolbarConfig: {
					excludeKeys: ['direction', 'date', 'lineHeight', 'letterSpacing', 'listCheck'],
					iconSize: '14px',
					iconColumns: 10
				},
				mediaQueryOb: null // 响应式媒体查询
			}
		},
		onLoad(opt) {
			if (opt.goods_id) this.goods_id = opt.goods_id;
			this.getClassify();


		},
		onShow() {
			this.testMediaQueryObserver();
		},

		methods: {
			// 获取输入内容
			inputOver(e, index) {
				this.ruleForm[index].value = e.html;
				// console.log(index,'index');
				// console.log('==== inputOver :', e)
			},

			initEditor(editor, value) {
				this.editorIns = editor // 保存编辑器实例
				const newHtml = this.addDomainToImgSrc(value, this.imgUrl);
				this.preRender(newHtml);
			},
			// 初始化编辑器内容
			preRender(newHtml) {
				this.editorIns.setContents({
					html: newHtml
				})
			},
			addDomainToImgSrc(html, domain) {
				const regex = /<img[^>]+src="([^"]+)"/g;
				return html.replace(regex, (match, src) => {
					// 如果src已经是一个完整的URL（包含http或https），则不添加域名  
					if (/^(http|https):\/\//.test(src)) {
						return match;
					}

					// 否则，给src添加域名  
					return match.replace(src, domain + src);
				});
			},
			upinImage(tempFiles, editorCtx) {
				let that = this;
				console.log(tempFiles, 'tempFiles');
				tempFiles.forEach(item => {
					that.$showLoading('上传中请稍后~');
					that.$common.uploadFiles(item.path).then(result => {
						const Url = result.url.slice(22);
						editorCtx.insertImage({
							src: that.$imgUrls(Url),
							width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
							success: function(e) {
								that.$hideLoading();
							}
						})
					})
				})


			},
			testMediaQueryObserver() {
				this.mediaQueryOb = uni.createMediaQueryObserver(this)
				this.mediaQueryOb.observe({
						minWidth: 0, //页面最小宽度 0px
						maxWidth: 500 //页面宽度最大 500px
					},
					(matches) => {
						// console.log('==== 开启媒体查询 :', matches)
						if (matches) {
							// 页面宽度在0-500px时
							this.toolbarConfig.iconColumns = 12
						} else {
							this.toolbarConfig.iconColumns = 16
						}
					}
				)
			},
			getGoodsInfo() {
				this.$http.post({
					url: '/singleSale/getGoodsInfo',
					data: {
						bid: this.bid,
						uid: this.uid,
						'postArr[goods_id]': this.goods_id,
					}
				}).then(res => {
					if (res.code != '100') return this.$Toast(res.msg);
					const result = res.uidData || [];
					this.ruleForm = result;
					if (!this.goods_id) return;
					const Index = this.ruleForm.findIndex(e => e.type == 1);
					const classifyName = this.findClassifyName(this.classify[0], this.ruleForm[Index].value);
					if (classifyName) this.ruleForm[Index].title = classifyName;
				})
			},
			findClassifyName(Data, targetId) {
				for (let item of Data) {
					if (item.classify_id == targetId) {
						return item.classify_name;
					}
					if (Array.isArray(item.children)) {
						let foundInChildren = this.findClassifyName(item.children, targetId);
						if (foundInChildren) return foundInChildren;
					}
				}

				return '';
			},
			getClassify() {
				this.$http.post({
					url: '/singleSaleManageApi/getClassify',
					data: {
						shop_id: uni.getStorageSync('store_id')
					}
				}).then(res => {
					if (res.code != '200') return this.$Toast(res.msg);
					const result = res.data || [];
					this.classify[0] = result;
					this.classify[1] = [];
					this.classify[2] = [];
					this.getGoodsInfo();
				})
			},



			Upload(count, index) {
				let that = this;
				uni.chooseImage({
					count,
					success: (res) => {
						const tempFilePaths = res.tempFilePaths;
						tempFilePaths.forEach(item => {
							that.$common.uploadFiles(item).then(result => {
								const Url = result.url.slice(22);
								that.ruleForm[index].value.push(Url);
							})
						})
					}
				})
			},

			closeImg(index, sindex) {
				this.ruleForm[index].value.splice(sindex, 1);
			},



			columnchange(e) {
				if (e.detail.column >= 2) return;
				if (!this.classify[e.detail.column].length) return;
				if (this.classify[e.detail.column][e.detail.value].children) {
					this.classify[e.detail.column + 1] = this.classify[e.detail.column][e.detail.value].children;
				} else {
					if (e.detail.column == 0) {
						this.classify[1] = [];
						this.classify[2] = [];
					} else {
						this.classify[e.detail.column + 1] = []
					}
				}
			},
			changeClass(e, current) {
				let result = e.detail.value;
				let nameArr = [];
				let lastElemnet = '';
				result.forEach((item, index) => {
					if (item != 0) nameArr.push(this.classify[index][item].classify_name)
				})
				result.forEach(item => {
					if (result[result.length - 1] == 0) {
						result = result.slice(0, -1);
					}
				})
				lastElemnet = result[result.length - 1];
				this.ruleForm[current].value = this.classify[result.length - 1][lastElemnet].classify_id;
				this.ruleForm[current].title = nameArr.join(' / ');
			},

			RadioBtn(ditem, index, dindex) {
				this.ruleForm[index].value = ditem.value;
			},


			subMit() {
				let result = {
					'type': 'addGoods',
					'bid': this.bid,
					'uid': this.uid,
					'postArr[storeId]': this.shopId,
					'postArr[goods_id]': this.goods_id,
				};
				for (let item of this.ruleForm) {
					if (!item.required) continue;
					if (!item.value || !item.value.length) return this.$Toast(`${item.title || item.placeholder}不能为空~`);
				}
				for (let item of this.ruleForm) {
					if (item.type == 5) {
						result[`postArr[${item.field_name}]`] = item.value.join();
					} else {
						result[`postArr[${item.field_name}]`] = item.value;
					}
				}
				this.$http.post({
					url: '/singleSale/singleSaleEdit',
					data: result
				}).then(res => {
					if (res.code != '100') return this.$Toast(res.msg);
					this.$Toast(res.msg);
					if (!this.goods_id) this.reset();
				})

			},

			reset() {
				for (let item of this.ruleForm) {
					if (item.type == 2) continue;
					if (item.type == 1) {
						item.title = '';
					} else if (item.type == 5) {
						item.value = [];
					} else if (item.type == 6) {
						item.value = [];
						this.preRender('');
					} else {
						item.value = '';
					}
				}
			},

		},
		computed: {
			...mapState(['uid', 'bid', 'shopId']),
		},
		destroyed() {
			this.mediaQueryOb.disconnect() //组件销毁时停止媒体查询监听
			this.mediaQueryOb = null
		},
	}
</script>

<style>
	page {
		background-color: #f8fafb;
	}
</style>
<style lang="scss">
	.list {
		width: 100%;
		height: 80rpx;
		background-color: #ffffff;
		border-radius: 10rpx;
		padding-left: 14rpx;
		position: relative;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.required::after {
		content: '*';
		height: auto;
		display: block;
		font-size: 40rpx;
		color: $color;
		position: absolute;
		left: 14rpx;
		top: 20rpx;
		overflow: hidden;
	}

	.viewData {
		flex: 1;
		height: 100%;
		margin-left: 30rpx;
		margin-right: 20rpx;
		display: flex;
		align-items: center;
	}

	.viewPicker {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
		display: flex;
		align-items: center;
	}

	.rightMore {
		width: 28rpx;
		height: 28rpx;
	}

	.Default {
		color: #666;
	}

	.list_medium {
		width: 100%;
		padding: 20rpx;
		background-color: #ffffff;
		border-radius: 10rpx;
		margin-bottom: 20rpx;
		position: relative;
	}

	.title {
		width: 100%;
		position: relative;
		padding-left: 30rpx;
		color: #808080;
		display: flex;
		align-items: center;
	}

	.required_med::after {
		content: '*';
		height: auto;
		display: block;
		font-size: 40rpx;
		color: $color;
		position: absolute;
		left: 0rpx;
		top: 0;
		overflow: hidden;
	}

	.list_imgs {
		position: relative;
		margin-top: 24rpx;
		margin-right: 24rpx;
		margin-left: 10rpx;
	}

	.list_imgs:nth-child(4n) {
		margin-right: 0;
	}

	.upload {
		width: 130rpx;
		height: 130rpx;
		border-radius: 8rpx;
	}

	.Close {
		width: 36rpx;
		height: 36rpx;
		background-color: #ffffff;
		border-radius: 50%;
		position: absolute;
		top: -14rpx;
		right: -6rpx;
		z-index: 10;
		display: block;
		overflow: hidden;
	}

	.textarea {
		width: 100%;
		height: 300rpx;
		border: 1rpx solid #ddd;
		border-radius: 10rpx;
		margin-top: 20rpx;
		padding: 20rpx;
		font-size: 24rpx;
		color: #333333;
	}

	.bot_btn {
		width: 260rpx;
		height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 30rpx;
		border-radius: 10rpx;
		letter-spacing: 6rpx;
	}

	.subMit {
		background-color: $color;
		color: #fff;
	}

	.reSet {
		background-color: #EAEAEA;
		color: #999;
	}

	.radio {
		display: flex;
		align-items: center;
		margin-top: 10rpx;
		margin-right: 14rpx;
		padding: 14rpx;
	}

	.radioName {
		color: #333;
		font-size: 24rpx;
		padding-right: 10rpx;
	}

	.radioRound {
		width: 28rpx;
		height: 28rpx;
		border-radius: 50%;
		border: 1rpx solid #ddd;
		display: flex;
		justify-content: center;
		align-items: center;
		position: relative;
	}

	.radioActive .radioRound {
		border: 1rpx solid $color !important;
	}

	.radioActive .radioRound::after {
		content: '';
		width: 12rpx;
		height: 12rpx;
		border-radius: 50%;
		background-color: $color;
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
	}
</style>